//
//  LBRCIMManager.m
//  app
//
//  Created by 刘文扬 on 16/8/26.
//  Copyright © 2016年 广东联结电子商务有限公司. All rights reserved.
//

#import "LBRCIMManager.h"
#import "RongIMKit/RongIMKit.h"
#import "LBIMUserInfoDataSource.h"
#import "LBDiscussBidMessage.h"
#import "LBJobInnerMessage.h"
#import "LBRongYunKitHead.h"
#import <LBDataCache.h>
#import <MJExtension.h>

@interface LBRCIMManager ()<RCIMConnectionStatusDelegate>

@end

@implementation LBRCIMManager

-(instancetype)init
{
    self = [super init];
    if (self) {
        
        _rcIMInfo = [LBDataCache getDataByClass:[LBRCIMInfo class] key:@"LBRCIMInfoModel"];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appLoginSuccess:) name:@"kNoficationKeyLoginSuccess" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appLogout:) name:@"kNoficationKeyLogout" object:nil];
    }
    return self;
}

-(void)appLoginSuccess:(id)sender
{
    [LBRCIMManager requestRongYunToken];
}

-(void)appLogout:(id)sender
{
    [LBRCIMManager logout];
}

+(instancetype)shareInstance
{
    static __kindof LBRCIMManager *sharedManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedManagerInstance=[[super allocWithZone:NULL] init];
    });
    
    return sharedManagerInstance;
}


-(BOOL)saveRCIMInfo{
    return [LBDataCache saveDataToDB:self.rcIMInfo key:@"LBRCIMInfoModel"];
}

+(void)configureRongYun
{
    //开启用户信息和群组信息的持久化
    [RCIM sharedRCIM].enablePersistentUserInfoCache = YES;
    
    [[RCIM sharedRCIM] setGlobalMessageAvatarStyle:RC_USER_AVATAR_CYCLE];
    //设置用户信息源和群组信息源
    LBIMUserInfoDataSource *dataSource = [LBIMUserInfoDataSource shareInstance];
    [RCIM sharedRCIM].receiveMessageDelegate = [LBRCIMManager shareInstance];
    [RCIM sharedRCIM].userInfoDataSource = dataSource;
    //    [RCIM sharedRCIM].groupMemberDataSource = dataSource;
    [RCIM sharedRCIM].connectionStatusDelegate = [LBRCIMManager shareInstance];
    
    // 注册自定义测试消息
    [[RCIM sharedRCIM] registerMessageType:[LBDiscussBidMessage class]];
    
    [[RCIM sharedRCIM] registerMessageType:[LBJobInnerMessage class]];
}

+(void)initializeRongYun
{
    [[RCIM sharedRCIM] initWithAppKey:[LBRCConfig RongYunKey]];
}

/**
 *  直接获取远程IM的token,用于过期的时候
 */
+(void)reqeustRongyunServiceIMToken
{
    [LBIMManager getIMTokenWithSuccess:^(NSString *token) {
        //请求远程token接口
        [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
            NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
        } error:^(RCConnectErrorCode status) {
            NSLog(@"登陆的错误码为:%ld", (long)status);
            //如果IM还是登录，无法登录融云，只能退出登录
            //                                [self loginOutSuccess:^(NSString *message) {
            //
            //                                } Fail:^(NSString *message) {
            //
            //                                }];
        } tokenIncorrect:^{
            //如果IM还是登录，无法登录融云，只能退出登录
            //                                [self loginOutSuccess:^(NSString *message) {
            //
            //                                } Fail:^(NSString *message) {
            //
            //                                }];
        }];
    } fail:^(NSString *message) {
        //如果IM的token还是获取不到，无法登录融云，只能退出登录
        //                            [self loginOutSuccess:^(NSString *message) {
        //
        //                            } Fail:^(NSString *message) {
        //
        //                            }];
    }];
    
}


+(void)requestRongYunToken;
{
    [LBIMManager getIMLocalTokenWithSuccess:^(NSString *token) {
        
        if (IsStrEmpty(token)) {
            
            //请求远程imtoken接口
            [LBIMManager getIMTokenWithSuccess:^(NSString *token) {
                
                [[self class] connectRongYunWithToken:token];
                
                
            } fail:^(NSString *message) {
                
            }];
        }else{
            [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
            } error:^(RCConnectErrorCode status) {
                NSLog(@"登陆的错误码为:%ld", (long)status);
            } tokenIncorrect:^{
                //token过期或者不正确。
                //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
                //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
                NSLog(@"token错误，清空token，准备再尝试一次");
                [LBRCIMManager shareInstance].rcIMInfo.imToken = nil;
                [LBIMManager getIMTokenWithSuccess:^(NSString *token) {
                    //请求远程token接口
                    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
                        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
                    } error:^(RCConnectErrorCode status) {
                        NSLog(@"登陆的错误码为:%ld", (long)status);
                        //如果IM还是登录，无法登录融云，只能退出登录
                        //                                [self loginOutSuccess:^(NSString *message) {
                        //
                        //                                } Fail:^(NSString *message) {
                        //
                        //                                }];
                    } tokenIncorrect:^{
                        //如果IM还是登录，无法登录融云，只能退出登录
                        //                                [self loginOutSuccess:^(NSString *message) {
                        //
                        //                                } Fail:^(NSString *message) {
                        //
                        //                                }];
                    }];
                } fail:^(NSString *message) {
                    //如果IM的token还是获取不到，无法登录融云，只能退出登录
                    //                            [self loginOutSuccess:^(NSString *message) {
                    //
                    //                            } Fail:^(NSString *message) {
                    //
                    //                            }];
                }];
            }];
        }
        
        
        
        
    } fail:^(NSString *message) {
        NSLog(@"%@",message);
        //如果IM的token获取不到，无法登录融云，就必须退出登录
        //                [self loginOutSuccess:^(NSString *message) {
        //
        //                } Fail:^(NSString *message) {
        //
        //                }];
    }];
}

+(void)reConectRongYun
{
    NSString *imtoken = [LBRCIMManager shareInstance].rcIMInfo.imToken;
    if (IsStrEmpty(imtoken)) {
        return;
    }
    [[RCIM sharedRCIM] connectWithToken:imtoken success:^(NSString *userId) {
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
    }];
}

+(void)connectRongYunWithToken:(NSString *)token
{
    [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
        NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
    } error:^(RCConnectErrorCode status) {
        NSLog(@"登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"token错误，清空token，准备再尝试一次");
        [LBRCIMManager shareInstance].rcIMInfo.imToken = nil;
        [LBIMManager getIMTokenWithSuccess:^(NSString *token) {
            //请求远程token接口
            [[RCIM sharedRCIM] connectWithToken:token success:^(NSString *userId) {
                NSLog(@"登陆成功。当前登录的用户ID：%@", userId);
            } error:^(RCConnectErrorCode status) {
                NSLog(@"登陆的错误码为:%ld", (long)status);
                //如果IM还是登录，无法登录融云，只能退出登录
                //                                [self loginOutSuccess:^(NSString *message) {
                //
                //                                } Fail:^(NSString *message) {
                //
                //                                }];
            } tokenIncorrect:^{
                //如果IM还是登录，无法登录融云，只能退出登录
                //                                [self loginOutSuccess:^(NSString *message) {
                //
                //                                } Fail:^(NSString *message) {
                //
                //                                }];
            }];
        } fail:^(NSString *message) {
            //如果IM的token还是获取不到，无法登录融云，只能退出登录
            //                            [self loginOutSuccess:^(NSString *message) {
            //
            //                            } Fail:^(NSString *message) {
            //
            //                            }];
        }];
    }];
}

-(BOOL)onRCIMCustomLocalNotification:(RCMessage *)message withSenderName:(NSString *)senderName
{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(onRCIMCustomLocalNotificationWithManager:message:withSenderName:)]) {
        return [self.delegate onRCIMCustomLocalNotificationWithManager:[LBRCIMManager shareInstance] message:message withSenderName:senderName];
    }
    return YES;
    
//    if (message.conversationType == ConversationType_SYSTEM){
//        if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
//
//            //程序内收到消息推送
//            return YES;
//
//        }
//
//        RCTextMessage *messageContent = (RCTextMessage *)message.content;
//        LBMessageExtraModel *extraModel = [LBMessageExtraModel mj_objectWithKeyValues:messageContent.extra];
//        if (extraModel.categorySecond == 0) {
//            //如果是刷新消息,不弹通知
//            return YES;
//        }
//
//        //        if (extraModel.category == LBMessageTypeBidEmploy) {
//        //            if (extraModel.categorySecond == LBJobMessageSecondTypeKickInterviewer || extraModel.categorySecond == LBJobMessageSecondTypeKickCandidate || extraModel.categorySecond == LBJobMessageSecondTypeJoinVideoMeeting) {
//        //                return YES;
//        //            }
//        //        }
//
//
//        [self addLocalNotificationWithMessage:message];
//    }
//    return YES;
}

-(BOOL)onRCIMCustomAlertSound:(RCMessage*)message
{
    return YES;
}


-(void)onRCIMReceiveMessage:(RCMessage *)message left:(int)left
{
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(didReceiveMessageWithManager:message:left:)]) {
        [self.delegate didReceiveMessageWithManager:[LBRCIMManager shareInstance] message:message left:left];
    }
    
    
    //    if (message.conversationType == ConversationType_SYSTEM) {
    //        RCTextMessage *messageContent = (RCTextMessage *)message.content;
    //        LBMessageExtraModel *extraModel = [LBMessageExtraModel mj_objectWithKeyValues:messageContent.extra];
    //        if (extraModel.category == LBMessageTypeBidTender) {
    //            [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyBidTenderNodeUpdate object:nil];
    //        }else if (extraModel.category == LBMessageTypeBidResource){
    //            if (extraModel.categorySecond == LBResourceMessageSecondTypeRealName) {
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyRealNameAuth object:nil];
    //            }
    //        }else if (extraModel.category == LBMessageTypeSystem) {
    //            if (extraModel.categorySecond == LBSystemMessageSecondTypeCooperation) {
    //
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyCooperativePartner object:nil];
    //
    //            }
    //        }else if (extraModel.category == LBMessageTypeBidTask){
    //
    //            if (extraModel.categorySecond == LBTaskMessageSecondTypeRefresh) {
    //                [LBTaskModelManager refreshDataFromIM:YES];
    //            }
    //        }else if (extraModel.category == LBMessageTypeBidEmploy){
    //            NSLog(@"%ld",(long)extraModel.categorySecond);
    //            if (extraModel.categorySecond == LBJobMessageSecondTypeRefresh) {
    //                [LBJobModelManager refreshData];
    //            }else if (extraModel.categorySecond == LBJobMessageSecondTypeFinishChat){
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyFinishChat object:nil];
    //            }else if (extraModel.categorySecond == LBJobMessageSecondTypeKickInterviewer){
    //
    //                //增加删除面试官的时候
    //
    //                NSDictionary *batchIdDic = @{@"batchId":LBStringNotNil(extraModel.batchId)};
    //
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyJobKickInterviewer object:nil userInfo:batchIdDic];
    //
    //
    //            }else if (extraModel.categorySecond == LBJobMessageSecondTypeKickCandidate){
    //
    //                NSDictionary *batchIdDic = @{@"batchId":LBStringNotNil(extraModel.batchId)};
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyJobKickCandidate object:nil userInfo:batchIdDic];
    //
    //            }else if (extraModel.categorySecond == LBJobMessageSecondTypeJoinVideoMeeting){
    //
    //                NSDictionary *batchIdDic = @{@"batchId":LBStringNotNil(extraModel.batchId)};
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyJobJoinVideoMeeting object:nil userInfo:batchIdDic];
    //
    //            }else if (extraModel.categorySecond == LBJobMessageSecondTypeCalling){
    //
    //                if ([[NSDate date] timeIntervalSince1970] - ((message.sentTime / 1000)) > 60) {
    //                    return;
    //                }
    //
    //                MAIN(^{
    //                    [LBJobModelManager presentCallingViewControllerWithData:extraModel];
    //                });
    //
    //
    //            }
    //        }else if (extraModel.category == LBMessageTypeOrder){
    //            if (extraModel.categorySecond == LBOrderMessageSecondTypeRefresh) {
    //
    //                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationKeyOrderNodeStateChange object:nil];
    //
    //            }
    //        }
    //
    //
    //    }else if(message.conversationType == ConversationType_GROUP){
    //
    //        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationKeyLBIMMessage object:message];
    //
    //    }else if(message.conversationType == ConversationType_PRIVATE){
    //
    //        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationKeyLBIMMessage object:message];
    //    }
    
}

-(void)addLocalNotificationWithMessage:(RCMessage *)message{
    
//    //定义本地通知对象
//    UILocalNotification *notification=[[UILocalNotification alloc]init];
//    //设置调用时间
//    //    notification.repeatInterval=2;//通知重复次数
//    //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历，使用前最好设置时区等信息以便能够自动同步时间
//    
//    //设置通知属性
//    
//    NSString *notificationContent = nil;
//    if ([message.objectName isEqualToString:RCTextMessageTypeIdentifier]) {
//        RCTextMessage *textMessage = (RCTextMessage *)message.content;
//        
//        notificationContent = textMessage.content;
//    }else{
//        notificationContent = @"有一条新的消息";
//    }
//    
//    
//    notification.alertBody = notificationContent; //通知主体
//    //    notification.applicationIconBadgeNumber=1;//应用程序图标右上角显示的消息数
//    //    notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
//    //    notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片
//    //    //notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音，默认消息声音
//    notification.soundName=@"msg.caf";//通知声音（需要真机）
//    
//    //设置用户信息
//    LBPushMessageData *pushData = [[LBPushMessageData alloc] init];
//    pushData.mId = message.messageId;
//    pushData.cType = @"SYS";
//    
//    
//    id extra = [message.content valueForKey:@"extra"];
//    LBMessageExtraModel *appData = [LBMessageExtraModel mj_objectWithKeyValues:extra];
//    
//    notification.userInfo=@{@"rc": [pushData mj_JSONString],@"appData":[appData mj_JSONString]};//绑定到通知上的其他额外信息
//    
//    //调用通知
//    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

-(void)onRCIMConnectionStatusChanged:(RCConnectionStatus)status
{
    if (status == ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT) {
        //您的账号在其他设备上已登录
        [LBRCIMManager shareInstance].rcIMInfo = nil;
        [[LBRCIMManager shareInstance] saveRCIMInfo];
        [LBRCIMManager logout];
        if (self.delegate && [self.delegate respondsToSelector:@selector(onKickWithManager:)]) {
            [self.delegate onKickWithManager:[LBRCIMManager shareInstance]];
        }
        //        [LBAlert say:^(NSInteger answer){
        //
        //        } message:@"您的账号在其他设备上已登录"];
        
    }else if (status == ConnectionStatus_TOKEN_INCORRECT) {
        [LBRCIMManager reqeustRongyunServiceIMToken];
    }
}

+(void)logout
{
    [[RCIM sharedRCIM] logout];
}


+(RCMessage *)getMessageByMId:(long)mId
{
    return [[RCIMClient sharedRCIMClient] getMessage:mId];
}

+(void)sendTextMessageWithTargetIds:(NSMutableArray *)targetIds content:(NSString *)content
{
    for (NSString *targetId in targetIds) {
        RCTextMessage *textMessage = [RCTextMessage messageWithContent:content];
        [[RCIM sharedRCIM] sendMessage:ConversationType_GROUP targetId:targetId content:textMessage pushContent:content pushData:nil success:^(long messageId) {
            
        } error:^(RCErrorCode nErrorCode, long messageId) {
            
        }];
    }
}

+(NSInteger)getUnReadCountBy:(RCConversationType)conversationType
                    targetId:(NSString *)targetId
{
    return [[RCIMClient sharedRCIMClient] getUnreadCount:conversationType  targetId:targetId];
}

+(NSInteger)getUnReadCount:(NSString *)targetId
{
    return [self getUnReadCountBy:ConversationType_GROUP targetId:targetId];
}



#pragma mark - 推送

+(void)setDeviceToken:(NSData *)deviceToken
{
    NSString *token = [[[[deviceToken description] stringByReplacingOccurrencesOfString:@"<"
                                                                             withString:@""]
                        stringByReplacingOccurrencesOfString:@">"
                        withString:@""]
                       stringByReplacingOccurrencesOfString:@" "
                       withString:@""];
    [[RCIMClient sharedRCIMClient] setDeviceToken:token];
}

@end


